﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SC_BLL;
using Top.Api.Util;

namespace Showcase
{
    public partial class LoginCallback : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString["top_appkey"] != null)
            {
                //关于回调地址：http://open.taobao.com/dev/index.php/%E8%8E%B7%E5%8F%96SessionKey
                //关于用户验证：http://open.taobao.com/dev/index.php/%E7%94%A8%E6%88%B7%E9%AA%8C%E8%AF%81
                //验证回调地址参数是否合法，如果合法并保存用户数据至Cookie
                if (TopUtils.VerifyTopResponse(Request.QueryString["top_parameters"], Request.QueryString["top_session"], Request.QueryString["top_sign"], Config.Appkey, Config.Secret) == true)
                {
                    //验证成功

                    //从top_parameters为解析当前回调地址登录的nick
                    string nick = GetParameters(Request.QueryString["top_parameters"].ToString(), "visitor_nick");
                    
                    Client.SetCookies(nick, Request.QueryString["top_session"].ToString());

                    Response.Redirect("index.aspx");
                }
                else
                {
                    //验证失败
                    Response.Write("无效验证！");
                }
            }
            else
            {
                Response.Write("无效参数对象，登录验证失败");
            }
        }

        /// <summary>
        /// 解析回调地址中top_parameters中的值
        /// </summary>
        /// <param name="key">取值关键词</param>
        /// <returns></returns>
        public string GetParameters(string parameters, string key)
        {
            string ret = string.Empty;
            try
            {
                string str = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(parameters));
                string[] param = str.Split('&');
                for (int i = 0; i < param.Length; i++)
                {
                    string[] info = param[i].Split('=');
                    if (info[0].ToLower() == key.ToLower())
                    {
                        ret = info[1];
                        break;
                    }
                }
            }
            catch (Exception exp)
            {
                //
            }
            return ret;
        }
    }
}